package com.example;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;

public class ExampleMain {
    public static EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
    public static void main(String[] args) {
        Employee employee = new Employee("Sara Dorsey","Admin");
        persistEntities(employee);
        employee.setDepartment("Account");
        updateEntities(employee);
        Employee employee2 = loadEmployeeById(employee.getId());
        System.err.println("Employee2 loaded:" + JSONObject.toJSONString(employee2,false));
        Employee employee3 = new Employee(employee.getId(),employee.getName(),"Sales");
        updateEntities(employee3);
        System.err.println("Employee3 loaded:" + JSONObject.toJSONString(employee3,false));
        Employee employee4 = new Employee(4,"JohnConnor","IT");
        updateEntities(employee4);
        Employee employee5 = new Employee("JamesGates","Sales");
        updateEntities(employee5);
        Employee employee7 = new Employee(5,"Mike","it");
        updateEntities(employee7);
        List<Employee> employees = emf.createEntityManager().createQuery("select e from Employee e").getResultList();
        System.err.println(JSONObject.toJSONString(employees,true));

    }
    private static Employee loadEmployeeById(Integer id){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.find(Employee.class,id);
        return employee;
    }
    private static void updateEntities(Employee employee){
        System.err.println("-------------- merging employee -------------------");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.merge(employee);
        em.getTransaction().commit();
        em.close();
        System.err.println("Employee Merged:" + JSONObject.toJSONString(employee,false));
    }
    private static void persistEntities(Employee employee){
        System.err.println("------------ persisting entities ---------------");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        em.close();
        System.err.println("Employee persisted:" + JSONObject.toJSONString(employee,false));
    }
}
